﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using AcceptanceTest.Framework;

namespace AcceptanceTest.MsTestSample
{
    [StepDefinition("MSTest")]
    public class MsTestSteps
    {
        private string output = "";

        [Config("MSTestExePath")]
        public string MSTestExePath { get; set; }

        [Config("MSTestContainerPath")]
        public string MSTestContainerPath { get; set; }

        [Step(@"^run (.+)$")]
        public void RunTests(string testContainerName)
        {
            if (string.IsNullOrEmpty(MSTestExePath))
            {
                MSTestExePath = @"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\mstest.exe";
            }

            if (!string.IsNullOrEmpty(MSTestContainerPath))
            {
                testContainerName = Path.Combine(MSTestContainerPath, testContainerName);
            }

            var pinfo = new ProcessStartInfo(MSTestExePath);
            pinfo.Arguments = "/nologo /noresults /testcontainer:\"" + testContainerName + "\"";
            pinfo.CreateNoWindow = true;
            pinfo.RedirectStandardError = pinfo.RedirectStandardOutput = true;
            pinfo.UseShellExecute = false;
            var process = Process.Start(pinfo);

            output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
        }

        [Step(@"^test (.+) should pass$")]
        public void CheckTestPass(string testName)
        {
            string pattern = string.Format(@"Passed (.+)\.{0}", testName);
            if (!Regex.IsMatch(output, pattern))
            {
                throw new Exception("Failed: " + testName);
            }
        }
    }

}
